<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row: ListData) => row.corName"
      :dataSource="dataform"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新建" style="width: 70%" >
      <n-space vertical :size="20">
        <n-space>
          <n-button @click="downloadCsv"> 导出 CSV </n-button>
        </n-space>
        <n-data-table
          ref="tableRef"
          :columns="infos"
          :data="datatable"
          :pagination="pagination"
          :bordered="false"
          :scroll-x = "1000"
          
        />
      </n-space>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '../../components/Table';
  import { BasicForm, FormSchema, useForm } from '../../components/Form/index';
  import { getCorInfo, getBasicInfo, getBaggage } from '../../api/dataInfo/flightInfo';
  import { columns, ListData } from './columns';
  import { infos } from './infos';
  import { DataTableInst } from 'naive-ui/es/data-table';
  import * as XLSX from 'xlsx';
import { ResultEnum, ipAddress } from '@/enums/httpEnum';
import { useMessage } from 'naive-ui';


  const schemas: FormSchema[] = [
    {
      field: 'corName',
      component: 'NSelect',
      label: '航空公司',
      rules: [{ required: true, message: '请选择航空公司', trigger: ['blur', 'input'] }],
      componentProps: {
        placeholder: '请选择航司',
        options: [],
        filterable: 'true',
      },
    },
    {
      field: 'flightNum',
      component: 'NInput',
      label: '航班号',
      rules: [
        {
          required: true,
          pattern: /^\d+$/, // 使用正则表达式匹配数字
          message: '请输入有效的航班号（只允许输入数字）',
          trigger: ['blur', 'input'],
        },
      ],
      componentProps: {
        placeholder: '请输入航班号',
        showButton: false,
      },
    },
    {
      field: 'startTime',
      component: 'NDatePicker',
      label: '起始时间',
      componentProps: {
        type: 'date',
        clearable: true,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'endTime',
      component: 'NDatePicker',
      label: '截至时间',
      componentProps: {
        type: 'date',
        clearable: true,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'inOrOut',
      component: 'NRadioGroup',
      label: '进出港',
      componentProps: {
        options: [
          {
            label: '进港',
            value: 'A',
          },
          {
            label: '出港',
            value: 'D',
          },
        ],
      },
    },
  ];
  const message = useMessage();
  const options = ref([]);
  const tableRef = ref<DataTableInst>();
  const actionRef = ref();
  const response = ref(null);
  const showModal = ref(false);
  const pagination = false as const;
  const dataform = ref([]);
  const formParams = reactive({
    corName: '',
    flightNum: '',
    startTime: '',
    endTime: '',
  });
  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '行李信息',
            onClick: lookInfo.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
          },
        ],
      });
    },
  });
  const downloadCsv = () => {
  const ws = XLSX.utils.json_to_sheet(datatable.value.map((item) => {
    // Map backend keys to corresponding column titles
    return {
      '行李转盘号': item.code,
      '出发类型': item.btat,
      '预计开始时间': item.estr,
      '预计结束时间': item.eend,
      '预计到达时间': item.eend,
      '实际开始时间': item.rstr,
      '实际结束时间': item.rend,
      '航站楼号': item.btsc,
    };
  }));

  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, 'data-table.xlsx');
};


  onMounted(async () => {
    try {
      response.value = await getCorInfo();

      // 将角色列表转换为 NSelect 组件的选项格式
      const CorOptions = response.value.data.map((cor) => ({
        label: cor.corCn + ' ' + cor.corEng,
        value: cor.corEng,
      }));

      // 在 formParams.corName 中设置初始值
      formParams.corName = CorOptions[0].label; // 如果需要，可以设置默认值
      options.value = CorOptions;

      // 找到角色类型字段的 schema 索引
      const corSchemaIndex = schemas.findIndex((schema) => schema.field === 'corName');

      // 如果找到了角色类型字段的 schema，则将角色选项设置到 componentProps.options 中
      if (corSchemaIndex !== -1) {
        schemas[corSchemaIndex].componentProps.options = CorOptions;
      }
    } catch (error) {
      console.error('获取角色数据失败', error);
    }
  });

  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  const loadDataTable = async (res) => {
    const rese = await getBasicInfo(getFieldsValue(), res.page, res.pageSize);
    if(rese.code == ResultEnum.SUCCESS){
      var matchedName = ipAddress[rese.msg];
      message.success('正在访问'+matchedName+'的接口');
    }
    return rese.data;
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }
  const datatable=ref();
  
 async function lookInfo(record: Recordable) {
  console.log(record);
  showModal.value = true;
  const res = await getBaggage(record.fide)
  datatable.value = res.data;
}


  function handleReset(values: Recordable) {
    console.log(values);
  }

  function handleSubmit(){
    reloadTable();
  }
</script>

<style lang="less" scoped></style>
